import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import type { 
  Friend, 
  FriendsState, 
  SearchFriendsRequest,
  FriendListResponse,
  UserStatus 
} from '@/types'
import { friendService } from '@/services/friend'

export const useFriendsStore = defineStore('friends', () => {
  // State
  const friends = ref<Friend[]>([])
  const onlineFriends = ref<number[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const searchResults = ref<Friend[]>([])
  const isSearching = ref(false)

  // Getters
  const friendsList = computed(() => friends.value)
  
  const onlineFriendsList = computed(() => {
    return friends.value.filter(friend => onlineFriends.value.includes(friend.id))
  })
  
  const offlineFriendsList = computed(() => {
    return friends.value.filter(friend => !onlineFriends.value.includes(friend.id))
  })
  
  const onlineCount = computed(() => onlineFriends.value.length)
  
  const totalCount = computed(() => friends.value.length)
  
  const getFriendById = computed(() => {
    return (friendId: number): Friend | undefined => {
      return friends.value.find(friend => friend.id === friendId)
    }
  })
  
  const searchResultsList = computed(() => searchResults.value)

  // Actions
  const loadFriends = async (): Promise<void> => {
    try {
      isLoading.value = true
      error.value = null

      const response = await friendService.getFriendList()
      
      friends.value = response.friends || []
      
      // Update online friends list
      onlineFriends.value = friends.value
        .filter(friend => friend.status === 'online')
        .map(friend => friend.id)
    } catch (err: any) {
      error.value = err.message || '加载好友列表失败'
    } finally {
      isLoading.value = false
    }
  }

  const searchFriends = async (request: SearchFriendsRequest): Promise<void> => {
    try {
      isSearching.value = true
      error.value = null

      const response = await friendService.searchFriends(
        request.keyword,
        request.page,
        request.pageSize
      )
      
      searchResults.value = response.items || []
    } catch (err: any) {
      error.value = err.message || '搜索好友失败'
    } finally {
      isSearching.value = false
    }
  }

  const addFriend = async (friendId: number): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      await friendService.addFriend(friendId)
      
      // Reload friends list to get updated data
      await loadFriends()
      return true
    } catch (err: any) {
      error.value = err.message || '添加好友时发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const removeFriend = async (friendId: number): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      await friendService.removeFriend(friendId)
      
      // Remove from local state
      friends.value = friends.value.filter(friend => friend.id !== friendId)
      onlineFriends.value = onlineFriends.value.filter(id => id !== friendId)
      return true
    } catch (err: any) {
      error.value = err.message || '删除好友时发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const blockFriend = async (friendId: number): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      // Note: This API doesn't exist yet, we'll need to implement it
      // For now, just update the local state
      const friendIndex = friends.value.findIndex(friend => friend.id === friendId)
      if (friendIndex !== -1) {
        friends.value[friendIndex].friendshipStatus = 'blocked'
        return true
      }
      return false
    } catch (err: any) {
      error.value = err.message || '屏蔽好友时发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const unblockFriend = async (friendId: number): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      // Note: This API doesn't exist yet, we'll need to implement it
      // For now, just update the local state
      const friendIndex = friends.value.findIndex(friend => friend.id === friendId)
      if (friendIndex !== -1) {
        friends.value[friendIndex].friendshipStatus = 'accepted'
        return true
      }
      return false
    } catch (err: any) {
      error.value = err.message || '取消屏蔽时发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const updateFriendStatus = (friendId: number, status: UserStatus): void => {
    const friendIndex = friends.value.findIndex(friend => friend.id === friendId)
    
    if (friendIndex !== -1) {
      friends.value[friendIndex].status = status
      friends.value[friendIndex].lastActiveTime = new Date()
      
      // Update online friends list
      if (status === 'online') {
        if (!onlineFriends.value.includes(friendId)) {
          onlineFriends.value.push(friendId)
        }
      } else {
        onlineFriends.value = onlineFriends.value.filter(id => id !== friendId)
      }
    }
  }

  const updateFriend = (friendData: Partial<Friend> & { id: number }): void => {
    const friendIndex = friends.value.findIndex(friend => friend.id === friendData.id)
    
    if (friendIndex !== -1) {
      friends.value[friendIndex] = { ...friends.value[friendIndex], ...friendData }
    }
  }

  const clearSearchResults = (): void => {
    searchResults.value = []
  }

  const clearError = (): void => {
    error.value = null
  }

  const refreshFriends = async (): Promise<void> => {
    await loadFriends()
  }

  // Batch update online status
  const updateOnlineFriends = (onlineUserIds: number[]): void => {
    onlineFriends.value = onlineUserIds.filter(id => 
      friends.value.some(friend => friend.id === id)
    )
    
    // Update individual friend status
    friends.value.forEach(friend => {
      const isOnline = onlineUserIds.includes(friend.id)
      if (friend.status !== (isOnline ? 'online' : 'offline')) {
        friend.status = isOnline ? 'online' : 'offline'
        friend.lastActiveTime = new Date()
      }
    })
  }

  return {
    // State
    friends: readonly(friends),
    onlineFriends: readonly(onlineFriends),
    isLoading: readonly(isLoading),
    error: readonly(error),
    searchResults: readonly(searchResults),
    isSearching: readonly(isSearching),
    
    // Getters
    friendsList,
    onlineFriendsList,
    offlineFriendsList,
    onlineCount,
    totalCount,
    getFriendById,
    searchResultsList,
    
    // Actions
    loadFriends,
    searchFriends,
    addFriend,
    removeFriend,
    blockFriend,
    unblockFriend,
    updateFriendStatus,
    updateFriend,
    clearSearchResults,
    clearError,
    refreshFriends,
    updateOnlineFriends
  }
})